package com.zwz.service.impl;

import com.zwz.service.DatabaseMetaService;
import com.zwz.voObject.DatabaseMetaVO.ColumnInfo;
import com.zwz.voObject.DatabaseMetaVO.TableInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class DatabaseMetaServiceImpl implements DatabaseMetaService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<TableInfo> getAllTableInfo() {
        String sql = "SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE()";
        List<String> tableNames = jdbcTemplate.queryForList(sql, String.class);
        
        return tableNames.stream()
                .map(this::getTableInfo)
                .collect(Collectors.toList());
    }

    @Override
    public TableInfo getTableInfo(String tableName) {
        String sql = "SELECT COLUMN_NAME, DATA_TYPE, COLUMN_COMMENT, IS_NULLABLE, COLUMN_KEY " +
                    "FROM information_schema.COLUMNS " +
                    "WHERE TABLE_SCHEMA = DATABASE() " +
                    "AND TABLE_NAME = ? " +
                    "ORDER BY ORDINAL_POSITION";
            
        List<ColumnInfo> columns = jdbcTemplate.query(sql, (rs, rowNum) -> {
            ColumnInfo column = new ColumnInfo();
            column.setColumnName(rs.getString("COLUMN_NAME"));
            column.setDataType(rs.getString("DATA_TYPE"));
            column.setColumnComment(rs.getString("COLUMN_COMMENT"));
            column.setIsNullable("YES".equals(rs.getString("IS_NULLABLE")));
            column.setIsPrimaryKey("PRI".equals(rs.getString("COLUMN_KEY")));
            return column;
        }, tableName);

        TableInfo tableInfo = new TableInfo();
        tableInfo.setTableName(tableName);
        tableInfo.setColumns(columns);
        
        return tableInfo;
    }
} 